package com.qf.flash.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.Group;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.constant.Constant;
import com.qf.flash.event.ChangeGroupEvent;
import com.qf.flash.http.response.GameDetailResponse;
import com.qf.flash.http.response.ScriptDetailResponse;
import com.qf.flash.model.CommentBean;
import com.qf.flash.model.Pay2JoinBean;
import com.qf.flash.model.PayParam;
import com.qf.flash.model.ScriptRoleBean;
import com.qf.flash.mvp.contract.CommentContract;
import com.qf.flash.mvp.contract.GameDetailContract;
import com.qf.flash.mvp.contract.ScriptDetailContract;
import com.qf.flash.mvp.contract.StartTeamContract;
import com.qf.flash.mvp.presenter.CommentPresenter;
import com.qf.flash.mvp.presenter.GameDetailPresenter;
import com.qf.flash.mvp.presenter.ScriptDetailPresenter;
import com.qf.flash.mvp.presenter.StartTeamPresenter;
import com.qf.flash.ui.chat.ChatActivity;
import com.qf.flash.ui.home.adapter.GameCommentView;
import com.qf.flash.ui.home.adapter.GroupMemberItem;
import com.qf.flash.ui.home.adapter.RoleItem;
import com.qf.flash.ui.mine.InviteFriendFragment;
import com.qf.flash.utils.ImageLoader;
import com.qf.flash.widget.RatingBarView;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.SpannableStringUtil;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.text.Html.FROM_HTML_MODE_COMPACT;

/**
 * 创建日期：2020/2/23 on 20:36
 * 描述: 组队详情
 * 作者:戴旭东
 */
public class GroupDetailActivity extends BaseActivity implements GameDetailContract.View, ScriptDetailContract.View, CommentContract.View, StartTeamContract.View {

    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_game_name)
    TextView tvGameName;
    @BindView(R.id.tv_group_no)
    TextView tvGroupNo;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.iv_open_close)
    ImageView ivOpenClose;
    @BindView(R.id.tv_introduce)
    TextView tvIntroduce;
    @BindView(R.id.tv_introduce_title)
    TextView tvIntroduceTitle;
    @BindView(R.id.tv_members)
    TextView tvMembers;
    @BindView(R.id.rv_members)
    RecyclerView rvMembers;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.rbv_star)
    RatingBarView rbvStar;
    @BindView(R.id.tv_total_comment)
    TextView tvTotalComment;
    @BindView(R.id.tv_role_title)
    TextView tv_role_title;
    @BindView(R.id.rv_role)
    RecyclerView rvRole;
    @BindView(R.id.rv_comment)
    RecyclerView rv_comment;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.tv_join)
    TextView tvJoin;
    @BindView(R.id.tv_empty_place)
    TextView tv_empty_place;
    @BindView(R.id.group_business_msg)
    Group group_business_msg;
    @BindView(R.id.cl_comment)
    ConstraintLayout cl_comment;
    @BindView(R.id.tv_gon_chat)
    TextView tvGonChat;
    private RVAdapter<Object> mCommentAdapter;
    private RVAdapter<Object> mMemberAdapter;
    private RVAdapter<ScriptRoleBean> mRoleAdapter;

    private GameDetailPresenter mGameDetailPresenter;
    private CommentPresenter mCommentPresenter;
    private ScriptDetailPresenter mScriptDetailPresenter;
    private StartTeamPresenter mStartTeamPresenter;

    private int page = 1;
    private String playId;
    private GameDetailResponse response;
    private boolean isOpen;   //是否展开
    private String id;

    /**
     * @param id     组队id
     * @param playId 剧本id
     */
    public static void start(Activity activity, String id, String playId) {
        Intent intent = new Intent(activity, GroupDetailActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("playId", playId);
        activity.startActivity(intent);
    }

    @Override
    protected void initInject() {
        mGameDetailPresenter = new GameDetailPresenter();
        mCommentPresenter = new CommentPresenter();
        mScriptDetailPresenter = new ScriptDetailPresenter();
        mStartTeamPresenter = new StartTeamPresenter();
        initPresenters(mGameDetailPresenter, mCommentPresenter, mScriptDetailPresenter, mStartTeamPresenter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group_detail;
    }

    @Override
    protected void initViewAndData() {
        tvTopTitle.setText("组队详情");
        initCommentRv();
        initMemberRv();
        initRvRole();
        initRefresh();
        id = getIntent().getStringExtra("id");
        playId = getIntent().getStringExtra("playId");
        mGameDetailPresenter.getGameDetail(id);
        if (TextUtils.isEmpty(playId)) {
            cl_comment.setVisibility(View.GONE);
        } else {
            cl_comment.setVisibility(View.VISIBLE);
            mCommentPresenter.getCommentData(playId, page);
        }

        if (TextUtils.isEmpty(playId)) {
            tvIntroduce.setVisibility(View.GONE);
            tv_role_title.setVisibility(View.GONE);
            rvRole.setVisibility(View.GONE);
            tvIntroduceTitle.setVisibility(View.GONE);
            cl_comment.setVisibility(View.GONE);
            rv_comment.setVisibility(View.GONE);
            ivOpenClose.setVisibility(View.GONE);
            mRefresh.setEnableLoadMore(false);
        } else {
            mScriptDetailPresenter.getScriptRole(playId);
        }


    }

    private void initRefresh() {
        mRefresh.setEnableRefresh(false);
        mRefresh.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mCommentPresenter.getCommentData(playId, page);
        });
    }


    private void initCommentRv() {
        rv_comment.setLayoutManager(new LinearLayoutManager(this));
        mCommentAdapter = new RVAdapter<>(new GameCommentView());
        rv_comment.setAdapter(mCommentAdapter);
    }

    private void initMemberRv() {
        rvMembers.setLayoutManager(new LinearLayoutManager(this));
        mMemberAdapter = new RVAdapter<>(new GroupMemberItem());
        rvMembers.setAdapter(mMemberAdapter);
        mMemberAdapter.setOnItemClickListener((view, position) -> {
            Object data = mMemberAdapter.getData(position);
            if (data instanceof GameDetailResponse.UsersBean) {
                GameDetailResponse.UsersBean bean = (GameDetailResponse.UsersBean) data;
                MemberMsgActivity.start(GroupDetailActivity.this, bean.getUid(), "");
            }
        });
    }

    private void initRvRole() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvRole.setLayoutManager(linearLayoutManager);
        mRoleAdapter = new RVAdapter<>(new RoleItem());
        rvRole.setAdapter(mRoleAdapter);
        mRoleAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                gotoRolePagerActivity(position);
            }
        });
    }

    private void gotoRolePagerActivity(int pos) {
        ArrayList<ScriptRoleBean> roleBeans = (ArrayList<ScriptRoleBean>) mRoleAdapter.getDatas();
        RolePagerActivity.start(this, roleBeans, pos);
    }

    @OnClick({R.id.tv_top_back, R.id.tv_join, R.id.cl_member, R.id.iv_open_close, R.id.tv_gon_chat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:
                finish();
                break;
            case R.id.tv_join:
                if (response == null) return;
                //加入组队
                if (response.getNeedNum() == response.getPayedNum()) {
                    FlashLib.showToast("组队已满");
                    return;
                }
                if (response.getIsSign() == 1) {
                    String orderState = response.getOrderState();
                    if (Integer.parseInt(orderState) >= 2) {
                        FlashLib.showToast("已完成组队");
                        return;
                    }
                    InviteFriendFragment.newInstance(response)
                            .setSize(278, 326)
                            .show(getSupportFragmentManager());
                } else {

                    if ("1".equals(response.getIsFree())) {
                        mStartTeamPresenter.joinTeam(response.getId());
                    } else {
                        Pay2JoinBean bean = new Pay2JoinBean();
                        bean.setGroupName(response.getTeamName());
                        bean.setTime(response.getGameTime());
                        bean.setMoney(response.getDownpayment());
                        bean.setCount(response.getNeedNum());
                        bean.setPassword(response.getGamePassword());
                        bean.setOrderId(response.getId());
                        GameDetailResponse.ShopBean shop = response.getShop();
                        if (shop != null)
                            bean.setBusiness(shop.getName());
                        Pay2JoinDialogFragment.newInstance(bean)
                                .show(getSupportFragmentManager());
                    }

                }

                break;
            case R.id.cl_member:
                if (response != null && !TextUtils.isEmpty(response.getShopId()))
                    BusinessDetailActivity.start(this,
                            response.getId(), response.getShopId(),
                            response.getEmchatId(), false);
                else if (response != null && TextUtils.isEmpty(response.getShopId())
                        && TextUtils.equals(response.getUserId(), UserMgr.getInstance().getLoginUser().getUid())) {
                    ChoseBusinessActivity.start(this, playId, this.response.getPlayType(), response.getId(), response.getEmchatId());
                }
                break;
            case R.id.iv_open_close:
                onArrowClick();
                break;
            case R.id.tv_gon_chat:
                if (response != null)
                    ChatActivity.goGroupChat(this, Constant.CHATTYPE_GROUP, response.getEmchatId());
                break;
        }
    }

    private void onArrowClick() {
        if (isOpen) {
            isOpen = false;
            tvIntroduce.setMaxLines(3);
            ivOpenClose.setRotation(0);
        } else {
            isOpen = true;
            tvIntroduce.setMaxLines(Integer.MAX_VALUE);
            ivOpenClose.setRotation(180);
        }
    }

    @Override
    public void setGDetail(GameDetailResponse response) {
        if (response == null)
            return;
        this.response = response;
        tvGameName.setText(response.getTeamName());
        tvGroupNo.setText(response.getOrderNumber());
        tvNickName.setText(response.getCaptainName());
        tvTime.setText(response.getGameTime());
        tvType.setText(response.getTypeName());
        tvAddress.setText(response.getShop().getLocation());
        ImageLoader.loadRoundCorners(this, response.getPlayImage(), ivImg, 5);
        String str = response.getPayedNum() + " / " + response.getNeedNum();
        SpannableStringBuilder stringBuilder = SpannableStringUtil.changeTextColor(str, Color.parseColor("#FABE00"), 0, 1);
        tvCount.setText(stringBuilder);
        tvMembers.setText("组队成员(" + response.getUsers().size() + ")");
        mMemberAdapter.setDatas(new ArrayList<>(response.getUsers()));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvIntroduce.setText(Html.fromHtml(response.getPlayDesc().replace("\n", "<br>"), FROM_HTML_MODE_COMPACT));
        } else {
            tvIntroduce.setText(Html.fromHtml(response.getPlayDesc().replace("\n", "<br>")));
        }
        //剧本评分
        tvScore.setText(response.getPlayScole() + "");
        rbvStar.setStar(Math.round(response.getPlayScole()), false);
        tvTotalComment.setText(response.getPlayCount() + "次评论");

        ImageLoader.loadCircleHead(this, response.getShop().getPhoto(), ivHead);
        if (TextUtils.isEmpty(response.getShopId())) {
            tv_empty_place.setVisibility(View.VISIBLE);
            group_business_msg.setVisibility(View.GONE);
        } else {
            tv_empty_place.setVisibility(View.GONE);
            group_business_msg.setVisibility(View.VISIBLE);
            tvName.setText(response.getShop().getName());
            tvLevel.setText("LV." + response.getShop().getLevel());
        }
        group_business_msg.requestLayout();
        //加入组队
        if (response.getNeedNum() == response.getPayedNum()) {
            tvJoin.setText("本队人员已满, 请选择其他组队");
            tvJoin.setTextColor(getResources().getColor(R.color.color_999999));

        } else if (response.getIsSign() == 1) {
            tvJoin.setText("邀请好友");
        } else {
            tvJoin.setText("加入组队");
        }
        if (1 == response.getIsNeedPlay()) {
            rvRole.setVisibility(View.VISIBLE);
            tv_role_title.setVisibility(View.VISIBLE);
            mScriptDetailPresenter.getScriptRole(playId);
        }
        showChatIcon(response);
    }

    private void showChatIcon(GameDetailResponse gameDetailBean) {
        if (gameDetailBean == null)
            return;
        String uid = UserMgr.getInstance().getLoginUser().getUid();
        for (GameDetailResponse.UsersBean user : gameDetailBean.getUsers()) {
            if (TextUtils.equals(uid, user.getUid())) {
                tvGonChat.setVisibility(View.VISIBLE);
                break;
            }
        }
    }

    @Override
    public void setCommentData(List<CommentBean> commentBeans, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh, false);
        List<Object> datas = mCommentAdapter.getDatas();
        datas.addAll(new ArrayList<>(commentBeans));
        mCommentAdapter.notifyDataSetChanged();
        mRefresh.setEnableLoadMore(page < totalPage);
    }

    @Override
    public void onError(ApiException e) {
        super.onError(e);
        ViewUtil.setRefreshComplete(mRefresh, false);
    }


    @Override
    public void setScriptDetail(ScriptDetailResponse response) {

    }

    @Override
    public void setScriptRole(List<ScriptRoleBean> roleBeans) {
        mRoleAdapter.setDatas(roleBeans);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void startSuccess(PayParam payParam) {
        OrderPaySuccessActivity.start(this, response.getId(), false);
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    @Subscribe
    public void onGroupChangeEvent(ChangeGroupEvent event) {
        mGameDetailPresenter.getGameDetail(id);
    }
}
